let templateRegExp = /\$\{(.+?)\}/g;
let hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";

export const stringUtils = {
    applyTemplate: function (template, attrs) {
        return template.replace(templateRegExp, ($0, $1) => {
            return attrs[$1] || $0;
        })
    },
    createReg: function (array) {
        return (array.length) ? new RegExp('^(' + array.join("|") + ')$') : /^$/;
    },
    uuid: function (len) {
        let uuids = [];
        for (let i = 0; i < len; i++) {
            uuids[i] = hexDigits.substr(Math.floor(Math.random() * 36), 1);
        }
        return uuids.join('');
    },
    urlJoin: function () {
        let input = arguments;
        let options = {};

        if (typeof arguments[0] === 'object') {
            input = arguments[0];
            options = arguments[1] || {};
        }
        input = Array.prototype.compact.call(input);
        let joined = [].splice.call(input, 0).join('/');
        return normalize(joined, options);
    },
    randomWord: function (randomFlag, min, max) {
        let str = "",
            range = min,
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
        // 随机产生
        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        let pos = -1;
        for (let i = 0; i < range; i++) {
            pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    }
};

function startWith(str, search) {
    return str.substr(0, search.length) === search;
}

function normalize(str, options) {
    if (startWith(str, 'file://')) {
        str = str.replace(/(\/{0,3})\/*/g, '$1');
    } else {
        str = str.replace(/:\//g, '://');
        str = str.replace(/([^:\s\%\3\A])\/+/g, '$1/');
    }
    str = str.replace(/\/(\?|&|#[^!])/g, '$1');
    str = str.replace(/(\?.+)\?/g, '$1&');
    return str;
}